package yxy.game.pm2.command.therionHunting;

import org.joda.time.DateTime;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankModule;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.TherionHuntingMessage;
import yxy.game.pm2.module.therionHunting.TherionChallengingPosition;
import yxy.game.pm2.module.therionHunting.TherionHandle;
import yxy.game.pm2.module.therionHunting.TherionModule;
import yxy.game.pm2.module.therionHunting.TherionPlayerModule;

import java.util.Map;

/**
 * @author wrs
 * @name CMD_TherionHuntingPosition
 * @descrition 神兽猎场挑战位
 * @since 2022-06-10
 */
@MessageType(proto = Command.TherionHuntingPosition, classtype = TherionHuntingMessage.TherionHuntingPositionRequest.class)
public class CMD_TherionHuntingPosition extends Command<TherionHuntingMessage.TherionHuntingPositionRequest> {

    @Override
    public void execute(MessageSource messageSource, TherionHuntingMessage.TherionHuntingPositionRequest request) throws Exception {
        String playerCode = messageSource.getTag();
        int gameType = request.getGameType(); //玩法类型；1：本服神兽争夺，2：跨服神兽猎场，3：跨服世界神兽
        int therionId = request.getTherionId(); //神兽ID
        int positionId = request.getPositionId(); //挑战位Id

        TherionHuntingMessage.TherionHuntingPositionResponse.Builder response = TherionHuntingMessage.TherionHuntingPositionResponse.newBuilder();

        TherionHandle handle = new TherionHandle();

        try {
            //神兽key
            int therionType = handle.getTherionKey(therionId);
            if (therionType == -1) {
                send(messageSource, response, Result.ParamError);
                return;
            }

            //具体玩法的某个神兽信息
            TherionModule therionModule = TherionModule.get(gameType, playerCode, therionType);
            if (therionModule == null) {
                send(messageSource, response, Result.DataError);
                return;
            }

            //是否还有挑战次数
            TherionPlayerModule playerModule = TherionPlayerModule.get(playerCode);
            if (playerModule == null) {
                send(messageSource, response, Result.DataError);
                return;
            }

            //判断是否在排行榜上，在排行榜上不需要检查 挑战次数
            boolean inRank = handle.isInRank(gameType, playerCode, therionType);
            if (playerModule.getChallengeNum().get(gameType) == 0 && !inRank) {
                send(messageSource, response, Result.ChallebgeNumNotEnough);//挑战次数不足
                return;
            }

            //获取指定挑战位
            TherionChallengingPosition position = TherionChallengingPosition.get(gameType, playerCode, therionType, positionId);
            if (position == null) {
                send(messageSource, response, Result.DataError);
                return;
            }

            //神兽的所有挑战位
            Map<Integer, TherionChallengingPosition> positionMap = TherionChallengingPosition.getAll(gameType, playerCode, therionType);
            if (positionMap == null) {
                send(messageSource, response, Result.DataError);
                return;
            }

            //todo 加锁改变位置状态和用户次数
            try {
                if (TherionChallengingPosition.lockTherionChallengingPosition(gameType, playerCode, therionType) ) {
                    //退出已占领的挑战位
                    Map<Integer, TherionChallengingPosition> allPositions = TherionChallengingPosition.getAll(gameType, playerCode, therionType);
                    for (TherionChallengingPosition pos : allPositions.values()) {
                        if (pos.getPlayCode() != null && pos.getPlayCode().equals(playerCode)) {
                            pos.setPlayCode(null);
                            pos.set(gameType, playerCode, therionType, pos.getPosition());
                            break;
                        }
                    }

                    if (position.getPlayCode() == null) {
                        position.setPlayCode(playerCode); //获得挑战位
                        position.setTime(DateTime.now()); //记录获得挑战位时间,用于计算伤害值
                        position.setOccupyTime(DateTime.now());//记录获得挑战位时间,用于计算占位时长
                        position.set(gameType, playerCode, therionType, positionId);
                    }

                    //排行榜上没有玩家信息，挑战次数 - 1
                    Integer num = playerModule.getChallengeNum().get(gameType);//挑战次数
                    if (!inRank && num > 0) {
                        playerModule.getChallengeNum().put(gameType, num - 1);
                        playerModule.set(playerCode);
                    }

                    TherionHandle.addValue(therionModule, gameType, playerCode, 1);

                    //剩余挑战次数
                    response.setChallengeNum(playerModule.getChallengeNum().get(gameType));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                TherionChallengingPosition.unlockTherionChallengingPosition(gameType, playerCode, therionType);

            }

            //统计并记录挑战人数
            int challengeNum = 0;
            for (TherionChallengingPosition value : positionMap.values()) {
                if (value.getPlayCode() != null) {
                    challengeNum++;
                }
            }
            therionModule.setChallengeNum(challengeNum);
            therionModule.set(gameType, therionType, playerCode);

            //封装排行榜和神兽信息
            RankModule rankModule = handle.getRankModule(gameType, playerCode, therionType);
            Result result = handle.packTherionBattleUiInfo(playerCode, therionModule, positionMap, rankModule, response);
            if (!result.equals(Result.Success)) {
                send(messageSource, response, result);
                return;
            }

            send(messageSource, response, Result.Success);

        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }

    }

    private void send(MessageSource messageSource, TherionHuntingMessage.TherionHuntingPositionResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}
